package edu.hawaii.duedates;

import java.util.ArrayList;
import java.util.List;

/**
 * The DueDates class accesses a given library for a given user to acquire the checked out items
 * information.  DueDates receives arguments from the command line that include the library to 
 * request information from, and the user id and the password belonging to required to log in to
 * the library's public web site.
 * 
 * DueDates works with the University of Hawaii and Hawaii State Library systems.
 * 
 * @author Ronn Reeves and Robin E. Raqueno
 */
public final class DueDates {

  // Create attributes for the University of Hawaii Library System
  private static final String UH_NAME = "UH Library System";
  private static final String UH_URL_SITE = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi";
  private static final String UH_URL_ARGS = "?DB=local&PAGE=pbLogon";
  private static final String UH_URL = UH_URL_SITE + UH_URL_ARGS;
  private static final String UH_FORM = "logonpage";
  private static final String UH_PASSWORD_FIELD = "LN";
  private static final String UH_USERID_FIELD = "BC";
  private static final String UH_LOGIN_ERROR = "Sorry, Login unsuccessful.";
  private static final String UH_NO_ITEMS = "You have no items checked out.";
  private static final String UH_TITLE_COL = "Item";
  private static final String UH_DATE_COL = "Status";
  
  // Create attributes for the Hawaii State Library System
  private static final String HI_NAME = "Hawaii State Library System";
  private static final String HI_URL = "http://www.librarieshawaii.org/";
  private static final String HI_PAGE_LINK = "My Account";
  private static final String HI_CHECK_OUT = "Checked Out";
  private static final String HI_PASSWORD_FIELD = "sec2";
  private static final String HI_USERID_FIELD = "sec1";
  private static final String HI_LOGIN_ERROR = "Login failed.";
  private static final String HI_NO_ITEMS = "Checked Out: 0";
  private static final String HI_TITLE_COL = "Title";
  private static final String HI_DATE_COL = "Due Date";

 
  /** Collection of libraries available for access. */
  private static final List<Library> libraries = new ArrayList<Library>();
  /** Collection of user credentials. */
  private static final List<User> users = new ArrayList<User>();
  /** Hawaii State Library Object. */
  private static final Library hi = 
    new Library(HI_NAME, HI_URL, HI_PASSWORD_FIELD, HI_USERID_FIELD);
  /** University of Hawaii Library Object. */
  private static final Library uh = 
    new Library(UH_NAME, UH_URL, UH_PASSWORD_FIELD, UH_USERID_FIELD);
  
  /** Singleton class constructor. */
  private DueDates() {
  }
  
  /**
   * Displays the requested checked out items information for the libraries and users passed to
   * DueDates from the command line.
   * 
   * @param args  The command line arguments passed to the program by the user.
   */
  public static void main(String[] args) {
    try { 
      if (((args.length < 3) && (args[0].startsWith("-"))) || ((args.length < 4) && 
          !(args[0].startsWith("-")))) {
        System.out.println("Required: -uhm <id> <lastname> or -hsl <barcode> <pin> or" + 
            " <uh id> <lastname>");
      }
      
      else {
        for (int index = 0; index < args.length; index++) {
          
          if (args[index].startsWith("-")) {
            createLibrary(args[index].substring(1));
            createUser(args[++index], args[++index]);
          }
          
          else {
            if (libraries.size() < 1) {
              createLibrary("uhm");
              createUser(args[index], args[++index]);
            }
            
            else if (libraries.size() < 2) {
              createLibrary("hsl");
              createUser(args[index], args[++index]);
            }
          }  
        }
      }  
    }
    
    catch (Exception e) {
      System.out.println(e.toString());
    }
    
    displayBooks();
  }
  
  
  /**
   * Creates the collection of libraries.
   * 
   * @param libraryCode The short name for a library. 
   */
  private static void createLibrary(String libraryCode) {
    if ("uhm".equals(libraryCode)) {
      // Add form name, login error message, and no items message attributes to UH Library
      uh.setFormName(UH_FORM);
      uh.setLoginErrorMessage(UH_LOGIN_ERROR);
      uh.setNoBorrowedItemsMessage(UH_NO_ITEMS);
      uh.setTitleColumn(UH_TITLE_COL);
      uh.setDateColumn(UH_DATE_COL);
      // Add UH Library to Libraries collection
      libraries.add(uh);
    }
    
    else if ("hsl".equals(libraryCode)) {
      // Add login page link and no items message to HI State Library
      hi.setLoginErrorMessage(HI_LOGIN_ERROR);
      hi.setLoginLink(HI_PAGE_LINK);
      hi.setSummaryLink(HI_CHECK_OUT);
      hi.setNoBorrowedItemsMessage(HI_NO_ITEMS);
      hi.setTitleColumn(HI_TITLE_COL);
      hi.setDateColumn(HI_DATE_COL);
      // Add HI State Library to Libraries collection
      libraries.add(hi);
    }
  }

  
  /**
   * Creates the user collection.
   * 
   * @param id The user's id.
   * @param password The user's password.
   */
  private static void createUser(String id, String password) {
    User user = new User(id, password);
    users.add(user);
  }
  
  /**
   * Displays the checked out items information for each user and library.
   */
  private static void displayBooks() {
    if (libraries.isEmpty()) {
      System.out.println("There were no libraries provided to check for borrowed items.");
    }
    else {
      for (int index = 0; index < libraries.size(); index++) {
        UserLibraryInfo uli = new UserLibraryInfo(users.get(index), libraries.get(index));
        uli.requestInfo();
        System.out.println(uli.getLibrary().toString());
        System.out.println("-------------------------------------------------------------------");
        if (uli.isValid()) {
          if (uli.getBooks().size() == 1) {
            System.out.printf("You have %s book checked out at this time.", 
                uli.getBooks().size()); 
          }
          else {
            System.out.printf("You have %s books checked out at this time.", 
              uli.getBooks().size()); 
          }
          if (!(uli.getBooks().isEmpty())) {
            System.out.println();
            System.out.println("Due Date    Title");
            for (Book book : uli.getBooks()) {
              if (book.getDueDate().length() > 10) {
                System.out.printf("%-12s", 
                  book.getDueDate().substring(book.getDueDate().length() - 8));
              }
              else {
                System.out.printf("%-12s", book.getDueDate());
              }
              System.out.println(book.getTitle());
            }
          }
        }
        
        else {
          System.out.printf("There was an issue connecting to the %s, or ", 
            uli.getLibrary().getName());
          System.out.printf("there was an issue logging in with the credentials for %s.\n",
            uli.getUser().getUserID());
          System.out.println("Please check the information passed and try again.");
        }
       
        System.out.println();
        System.out.println();
      }
    }
  }
}